package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;

import com.zzyl.nursing.amqp.IotMsgBody;
import com.zzyl.nursing.amqp.IotMsgNotifyData;
import com.zzyl.nursing.amqp.IotMsgService;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备警报信息Service业务层处理
 *
 * @author laoYe
 * @date 2025-10-29
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备警报信息
     *
     * @param id 设备警报信息主键
     * @return 设备警报信息
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备警报信息列表
     *
     * @param dto 设备警报信息
     * @return 设备警报信息集合
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto) {
        //设置分页参数
        Page<DeviceData> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        //按时间降序
        page.addOrder(OrderItem.desc("alarm_time"));
        //构建查询条件
        lambdaQuery().eq(StringUtil.isNotEmpty(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .eq(StringUtil.isNotEmpty(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .ge(ObjectUtils.isNotNull(dto.getStartTime()), DeviceData::getAlarmTime, dto.getStartTime())
                .le(ObjectUtils.isNotNull(dto.getEndTime()), DeviceData::getAlarmTime, dto.getEndTime())
                //查询数据
                .page(page);
        //封装结果返回
        return new TableDataInfo<DeviceData>(page.getTotal(), page.getRecords(), HttpStatus.HTTP_OK, "查询成功");
    }
    /**
     * 新增设备警报信息
     *
     * @param deviceData 设备警报信息
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备警报信息
     *
     * @param deviceData 设备警报信息
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备警报信息
     *
     * @param ids 需要删除的设备警报信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备警报信息信息
     *
     * @param id 设备警报信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 批量插入设备数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //获取设备上报的数据
        IotMsgBody body = iotMsgNotifyData.getBody();
        if (Objects.nonNull(body)) {
            List<IotMsgService> services = body.getServices();
            //不为空才需要添加到数据库中
            if (CollUtil.isNotEmpty(services)) {
                //检查设备是否存在，获取设备的ioId
                String ioId = iotMsgNotifyData.getHeader().getDeviceId();
                Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, ioId));
                if (Objects.nonNull(device)) {
                    //存在设备，创建一个list集合来存放数据信息
                    List<DeviceData> dataList = new ArrayList<>();
                    services.forEach(service -> {
                        String eventTime = service.getEventTime();
                        //上报时间
                        LocalDateTime alarmTime = LocalDateTimeUtil.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"))
                                .atZone(ZoneId.from(ZoneOffset.UTC))
                                //这个时间所在的时区是0时区，转成上海时区
                                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                                .toLocalDateTime();
                        //物理模型
                        Map<String, Object> dataMap = service.getProperties();
                        dataMap.forEach((key, value) -> {
                            //4条数据，4个对象
                            DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                            deviceData.setId(null);
                            deviceData.setCreateTime(null);
                            deviceData.setUpdateTime(null);
                            deviceData.setUpdateBy(null);
                            deviceData.setFunctionId(key);
                            deviceData.setDataValue(String.valueOf(value));
                            deviceData.setAlarmTime(alarmTime);
                            dataList.add(deviceData);
                        });

                    });
                    if (CollUtil.isNotEmpty(dataList)) {
                        saveBatch(dataList);
                        //存入redis中，方便查询
                        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,ioId, JSONUtil.toJsonStr(dataList));
                    }
                }
            }
        }
    }
}
